package com.momo.common.core.request;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 分页参数
 *
 * @author zuihou
 * @date 2020年02月14日16:19:36
 */
@Data
@ApiModel(value = "PageParams", description = "分页参数")
public class PageParams<T> {

    @NotNull(message = "查询对象model不能为空")
    @ApiModelProperty(value = "查询参数", required = true)
    private T model;

    @ApiModelProperty(value = "页面大小", example = "10")
    private long size = 10;

    @ApiModelProperty(value = "当前页", example = "1")
    private long current = 1;

    @ApiModelProperty(value = "排序,默认createTime", allowableValues = "", example = "id")
    private String sort = "id";

    @ApiModelProperty(value = "排序规则, 默认descending 倒叙,ascending 正序")
    private String order = "descending";

    private static final List<String> DEF_SORT = Arrays.asList("id", "createTime", "updateTime");

    @JsonIgnore
    public Page getPage() {
        return getPage(DEF_SORT);
    }

    @JsonIgnore
    public Page getPage(List<String> sortList) {
        PageParams params = this;
        if (StringUtils.isEmpty(params.getSort())) {
            Page page = new Page(params.getCurrent(), params.getSize());
            return page;
        }

        Page page = new Page(params.getCurrent(), params.getSize());
        List<OrderItem> orders = new ArrayList<>();
        if (sortList.contains(params.getSort())) {
            // 简单的 驼峰 转 下划线
            String sort = xX2x_x(params.getSort());
            orders.add("ascending".equals(params.getOrder()) ? OrderItem.asc(sort) : OrderItem.desc(sort));
            page.setOrders(orders);
        }

        return page;
    }

    /**
     * @param str
     * @return java.lang.String
     * @author Howe
     * @Description 将驼峰转为下划线
     * @Date 2022/4/22 13:11
     * @since 1.0.0
     */
    public static String xX2x_x(String str) {
        Pattern compile = Pattern.compile("[A-Z]");
        Matcher matcher = compile.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
